package com.dst.note.note_edit;

import android.app.Activity;
import android.arch.lifecycle.LifecycleOwner;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.view.WindowManager;
import android.widget.Toast;

import com.dst.note.model.Note;
import com.dst.note.model.NoteModel;
import com.dst.note.model.NoteSnap;
import com.dst.note.mvp.IPresenter;
import com.dst.note.mvp.IView;
import com.dst.note.route.Router;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created By tgl on 2019/2/21
 */
public abstract class EditNotePresenter extends IPresenter {
    private EditNoteMode mMode;
    private EditNoteView mView;
    private boolean isEditorBarEnable;
    private Note mNote;
    private String mNoteid;
    private boolean isNewNote;
    private MediaPlayer mMediaPlayer;

    public Note getNote() {
        return mNote;
    }

    public String getNoteid() {
        return mNoteid;
    }

    public EditNoteMode getMode() {
        return mMode;
    }

    public EditNotePresenter(Intent intent) {
        mNoteid = intent.getStringExtra("id");
    }

    public interface EditNoteView extends IView {
        void apply(Note mNote, int selectionStart, int selectionEnd);

        void writingMode(boolean isEditorBarEnable);

        void readingMode();

        void loadingMode();

        void finish();

        void setEditorbar(boolean isEnable);

        void insertImage(String url);

        void showFormatDialog();

        void showAlbumDialog();

        void showNetworkDialog();

        void showLoading();

        void hideLoading();
    }

    @Override
    public void onCreate(@NotNull LifecycleOwner owner) {
        this.mView = (EditNoteView) owner;
        this.isEditorBarEnable = true;
        this.isNewNote = false;
        this.mNote = null;
        this.loadNote();
    }

    private void loadNote() {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter emitter) {
                mNote = NoteModel.findNote((Context) mView, mNoteid);
                if (mNote == null) {
                    mNote = NoteModel.createNote((Context) mView);
                    emitter.onNext(true);
                } else {
                    NoteModel.openNote(mNote);
                    emitter.onNext(false);
                }
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        loadingMode();
                    }

                    @Override
                    public void onNext(Boolean isNew) {
                        isNewNote = isNew;
                        mView.apply(mNote, 0, 0);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        if (isNewNote) {
                            writingMode();
                        } else {
                            readingMode();
                        }
                    }
                });
    }

    @Override
    public void onDestroy(@NotNull LifecycleOwner owner) {
        this.mView = null;
    }

    public void tapTakePhoto() {
    }

    public void tapInsertUrl(String url) {
        mView.insertImage(url);
    }

    public void tapNetworkUrl() {
        mView.showNetworkDialog();
    }

    public void tapAlbum() {
        mView.showAlbumDialog();
    }

    public void tapEdit() {
        writingMode();
    }

    public void saveOrUpdate() {
        readingMode();
        updateNote();
    }

    public void tapBack() {
        if (mMode == EditNoteMode.Writing) {
            readingMode();
        } else {
            updateNote();
            mView.finish();
        }
    }

    public void tapMore() {

    }

    public abstract void voice();

    public void tapRecover(NoteSnap noteSnap) {
        if (noteSnap == null) {
            return;
        }
        mNote.setParagraphs(noteSnap.getParagraphs());
        mView.apply(mNote, noteSnap.getSelectionStart(), noteSnap.getSelectionEnd());
    }

    public void tapRetroke(NoteSnap noteSnap) {
        if (noteSnap == null) {
            return;
        }
        mNote.setParagraphs(noteSnap.getParagraphs());
        mView.apply(mNote, noteSnap.getSelectionStart(), noteSnap.getSelectionEnd());
    }


    public void tapImage(List<String> urls, int index) {
        if (mMode == EditNoteMode.Reading) {
            Router.with((Context) mView)
                    .intent("urls", urls)
                    .intent("index", index)
                    .route("imagePreview")
                    .go();
        }
    }

    public void tapAttach() {
        mView.showFormatDialog();
    }

    public void tapEditorBar(boolean isEnable) {
        isEditorBarEnable = isEnable;
        mView.setEditorbar(isEditorBarEnable);
    }

    private void loadingMode() {
        mMode = EditNoteMode.Loading;
        mView.loadingMode();

    }

    private void readingMode() {
        mMode = EditNoteMode.Reading;
        mView.readingMode();
    }

    private void writingMode() {
        mMode = EditNoteMode.Writing;
        mView.writingMode(isEditorBarEnable);
    }

    private void updateNote() {
        if (NoteModel.isNoteNull(mNote)) {
            NoteModel.deleteNote((Context) mView, mNote);
            if (!isNewNote) {
                Toast.makeText((Context) mView, "正在删除数据", Toast.LENGTH_SHORT).show();
            }
        } else if (mNote.isDirty()) {
            NoteModel.updateNote((Context) mView, mNote);
            Toast.makeText((Context) mView, "正在保存数据", Toast.LENGTH_SHORT).show();
            addAlarm(mNoteid, mNote.getReminderTime());
        }
    }

    /**
     * 添加闹钟
     *
     * @param time
     */
    public void addClock(long time) {
        mNote.setReminderTime(time);
        if (!mNote.isSetClock()) {
            cancelAlarm();
        }
        mNote.setDirty(true);
    }

    /**
     * 添加闹钟
     *
     * @param id
     * @param time
     */
    public abstract void addAlarm(String id, long time);

    public void cancelAlarm() {
        if (mNote.getReminderTime() > 0) {
            mNote.setDirty(true);
        }
        mNote.setReminderTime(0);
    }

    public void startPlaying(Activity activity, String path) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        } else if (mMediaPlayer.isPlaying()) {
            payerRelease();
            return;
        }
        try {
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
        } catch (IOException e) {
        }
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                payerRelease();
            }
        });
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    public void payerRelease() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
